package com.learn.thread;

import lombok.AllArgsConstructor;
import lombok.Data;

public class TestUnSafeThreadSynchronized4 {
    public static void main(String[] args) {
        AccountNew account = new AccountNew("中国工商银行",1000);
        new DrawMoneyThread(account, 1000, "小明").start();
        new DrawMoneyThread(account, 1000, "小红").start();
        new DrawMoneyThread(account, 1000, "小黄").start();
        new DrawMoneyThread(account, 1000, "小王").start();
        new DrawMoneyThread(account, 1000, "小赵").start();
        new DrawMoneyThread(account, 1000, "小钱").start();
    }
}

@AllArgsConstructor
@Data
class AccountNew {
    private String account;
    private int balance;
}

class DrawMoneyThread extends Thread {
    private AccountNew account;
    private int drawMoney;
    public DrawMoneyThread(AccountNew account, int drawMoney,String currentUser) {
        super(currentUser);
        this.account = account;
        this.drawMoney = drawMoney;

    }

    @Override
    public  void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        synchronized (account){
            if (account.getBalance() >= drawMoney){
                account.setBalance(account.getBalance()-drawMoney);
                System.out.println(Thread.currentThread().getName()+"取钱成功，取钱："+drawMoney+ " 余额 "+account.getBalance());
            }else {
                System.out.println(Thread.currentThread().getName()+"取钱失败，余额不足");
            }
        }

    }

}